<template>
  <section class="app-inner">
    <el-form :inline="true" ref="deviceForm" class="wrapper" :model="queryParams">
      <section class="justify-align">
        <div>
          <el-form-item>
            <el-button v-if="checkAuthority('/equipment/add')" type="primary" @click="handleAdd">新增设备</el-button>
            <el-button v-if="checkAuthority('/equipment/download')" type="primary" @click="downFile">下载模板</el-button>
            <el-upload
              style="display: inline; margin-left: 10px"
              :show-file-list="false"
              action="no"
              :before-upload="beforeUpload"
              :http-request="importExcel"
            >
            <el-button v-if="checkAuthority('/equipment/export')" type="primary" icon="import">批量导入</el-button>
            </el-upload>
          </el-form-item>
        </div>
        <div>
          <!-- 一级类型 -->
          <el-form-item>
            <el-select clearable filterable
            v-model="queryParams.eqptTypeId"
            @change="changeOneType"
            placeholder="全部一级类型">
            <el-option
              v-for="item in deviceOneTypeList"
              :key="item.typeId"
              :label="item.typeName"
              :value="item.typeId"
            ></el-option>
            </el-select>
          </el-form-item>

          <!-- 二级类型 -->
          <el-form-item>
            <el-select clearable filterable v-model="queryParams.twoLevelEqptTypeId" placeholder="全部二级类型">
            <el-option
              v-for="item in deviceTwoTypeList"
              :key="item.typeId"
              :label="item.typeName"
              :value="item.typeId"
            ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-input clearable placeholder="请输入设备名称" v-model="queryParams.eqptName"></el-input>
          </el-form-item>
          <el-form-item class="searchBtn">
            <el-button type="primary" @click="searchQuery">查询</el-button>
          </el-form-item>
        </div>
      </section>
    </el-form>
    <el-table :data="tableData" style="width: 100%" row-key="userNo">
      <el-table-column type="index" label="序号" width="80"></el-table-column>
      <el-table-column prop="sourceId" label="设备编号"></el-table-column>
      <el-table-column prop="firstLevelName" label="设备类型一级"></el-table-column>
      <el-table-column prop="secondLevelName" label="设备类型二级"></el-table-column>
      <el-table-column prop="eqptName" label="设备名称"></el-table-column>
      <el-table-column prop="supplierName" label="供应商"></el-table-column>
      <el-table-column prop="eqptAdress" label="地点"></el-table-column>
      <el-table-column prop="labelTreeName" label="标签">
        <template #default="{ row }">
          <ul v-for="(item, index) in row.labelTreeName" :key="index">
            <el-tooltip effect="dark" :content="item" placement="bottom">
              <div  class="ellipsis">{{ item }}</div>
            </el-tooltip>
          </ul>
        </template>
      </el-table-column>

      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button v-if="checkAuthority('/select')" type="text" size="small" @click="handleDetail(scope.row)">查看</el-button>
          <el-button v-if="checkAuthority('/equiment/editor')" type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button v-if="checkAuthority('/equiment/delete')" type="text" size="small" @click="handleRemove(scope.row)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>
    <el-pagination
      v-if="tableData.length > 0"
      style="text-align: right"
      layout="total, prev, pager, next"
      @current-change="pageHandleChange"
      :current-page="queryParams.current"
      :page-size="queryParams.pageSize"
      :total="totalPageNum"
    ></el-pagination>
    <maintain-modal
      v-if="dialogVisible"
      :eqptNo="eqptNo"
      ref="userModal"
      @ok="userModalOk"
    ></maintain-modal>
    <readMaintain ref="readDetail"></readMaintain>
  </section>
</template>

<script>
import MaintainModal from './MaintainModal'
import readMaintain from './readMaintain'
import {
  getEquipmentList,
  getDeviceTypeList,
  delEqptData,
  downDeviceTemplate,
  importDevice
} from '@/views/children/safety/js/device'
import { checkAuthority } from '@/utils/btnPermission' // 页面按钮权限

export default {
  name: 'DeviceMaintain',
  components: { MaintainModal, readMaintain },
  data () {
    return {
      dialogVisible: true,
      currentPage: 1,
      pageSize: 10,
      addFlag: false,
      totalPageNum: 0,
      queryParams: {
        areaId: '', // 区域id   ?
        areaName: '', // 区域名称  ?
        buildId: '', // 楼宇id  ?
        buildName: '', // 楼宇名称   ?
        current: 1, //  当前页
        eqptIds: [], // 设备id   ?
        eqptName: '', // 设备名称
        eqptTypeId: '', // 设备类型id
        floorId: '', // 楼层id
        floorName: '', // 楼层名称
        pageSize: 10, // 单页数量
        sourceId: '', //  供应商设备id
        supplierName: '', // 供应商名称
        twoLevelEqptTypeId: '' // 二级类型
      },
      judgeIdArr: [],
      deviceOneTypeList: [], // 设备一级类型
      deviceTwoTypeList: [],
      tableData: [],
      eqptNo: '',
      productNameList: []
    }
  },
  created () {
    this.searchQuery()
    this.getDeviceTypeList()
  },
  methods: {
    // 查询按钮
    checkAuthority,
    searchQuery () {
      this.queryParams.current = 1
      this.init()
    },

    // 获取设备信息
    async init () {
      try {
        let params = {
          ...this.queryParams
        }
        let res = await getEquipmentList(params)
        if (res.code === 0) {
          this.tableData = res.data.records
          this.totalPageNum = res.data.total
        } else {
          this.$message.warning(res.msg)
        }
      } catch (e) {}
    },
    // 获取设备一级类型下拉列表数据
    async getDeviceTypeList () {
      try {
        const params = {
          typeLevel: 1, // 类型名称
          typeParentId: '' // 父类型id
        }
        let res = await getDeviceTypeList(params)
        if (res.code === 0) {
          this.deviceOneTypeList = res.data
        } else {
          this.$message.warning(res.msg)
        }
      } catch (e) {}
    },

    // 获取设备二级类型下拉框数据
    async changeOneType (val) {
      console.log(val)
      try {
        const params = {
          typeLevel: 2, // 类型名称
          typeParentId: val // 父类型id
        }
        let res = await getDeviceTypeList(params)
        if (res.code === 0) {
          this.queryParams.twoLevelEqptTypeId = ''
          this.deviceTwoTypeList = res.data
        }
      } catch (e) {}
    },
    // 新增按钮
    handleAdd () {
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.userModal.add()
      })
    },
    // 查看详情
    handleDetail (row) {
      this.$refs.readDetail.add(row)
    },
    // 用户编辑
    handleEdit (row) {
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.userModal.edit(row)
      })
    },

    // 用户删除
    handleRemove (row) {
      this.$confirm('确定删除该设备吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let result = await delEqptData(row.eqptId)
        if (result.code === 0) {
          this.$message.success('删除成功！')
          await this.init()
        } else {
          this.$message.error(result.msg + '删除失败！')
        }
      })
    },

    // 用户CU弹框回调
    userModalOk () {
      this.init()
      this.$message.success('保存成功')
    },

    // 页码改变
    pageHandleChange (page) {
      this.queryParams.current = page
      this.init()
    },
    // 下载模板
    async downFile () {
      try {
        let res = await downDeviceTemplate()
        if (res.code === 0) {
          this.$message.success('下载中')
        }
      } catch (e) {}
    },
    // 导入前的验证
    beforeUpload (file) {
      const extension = file.name.split('.')[1] === 'xls'
      const extension2 = file.name.split('.')[1] === 'xlsx'
      const isLt2M = file.size / 1024 / 1024 < 200
      if (!extension && !extension2) {
        this.$message.warning('上传模板只能是 xls、xlsx格式!')
        return false
      } else if (!isLt2M) {
        this.$message.warning('上传模板大小不能超过 5MB!')
        return false
      } else {
        return true
      }
    },
    // EXCEL导入
    importExcel (file, fileList) {
      let headFile = file.file
      let formData = new FormData()
      formData.append('file', headFile)
      importDevice(formData).then((res) => {
        this.searchQuery()
        this.$message.success('导入成功')
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-line-clamp: 1;
}
.app-inner {
  .table-btn {
    margin-bottom: 15px;
    text-align: right;
  }
}
.no-hava {
  text-align: center;
  color: #cccccc;
}
.add-btn {
  margin-left: 10px;
}
.lose {
  background: #c8c9cc !important;
  cursor: not-allowed;
}
.tip-btn {
  margin-left: 15px;
  cursor: pointer;
  display: inline-block;
  span {
    font-size: 16px;
  }
  &:hover {
    color: #ff0000;
    .icon-question {
      border: 1px solid #ff0000;
    }
  }
  .tip-con {
    display: flex;
    align-items: center;
  }
  .icon-question {
    margin-left: 2px;
    width: 18px;
    height: 18px;
    border: 1px solid #333333;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
<style lang="scss">
.customConfirm {
  width: 480px;
  .el-message-box__content {
    text-align: left;
    padding: 20px 26px 26px 46px;
    li {
      height: 32px;
      line-height: 32px;
    }
  }
}
</style>
